<template>
  <div class="grading-table">
    <el-row>
      <el-col :span="24">
        <div class="header">
          <h1>成绩评定</h1>
        </div>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="22" :offset="1">
        <el-table :data="displayData" style="width: 100%" row-key="id" border>
          <el-table-column prop="groupName" label="组名" width="90px">
            <template #default="scope">
              <span v-if="scope.row.children" @click="toggle(scope.row)" style="cursor: pointer;">
                {{ scope.row.groupName }}
              </span>
              <span v-else>{{ scope.row.position }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="studentId" label="学号" width="100px"></el-table-column>
          <el-table-column prop="name" label="组长姓名" width="100px"></el-table-column>
          <el-table-column prop="initialGrade" label="初期成绩" width="150px">
            <template #default="scope">
              <span :style="getStyle(scope.row.initialScore)" @click="scope.row.children ? goToGradeEdit(scope.row, '初期成绩') : null" style="cursor: pointer;">
                {{ scope.row.initialScore !== 0.0 ? scope.row.initialScore : '待批阅' }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="midGrade" label="中期成绩" width="150px">
            <template #default="scope">
              <span :style="getStyle(scope.row.midTermScore)" @click="scope.row.children ? goToGradeEdit(scope.row, '中期成绩') : null" style="cursor: pointer;">
                {{ scope.row.midTermScore !== 0.0 ? scope.row.midTermScore : '待批阅' }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="finalGrade" label="终期成绩" width="150px">
            <template #default="scope">
              <span :style="getStyle(scope.row.finalScore)" @click="scope.row.children ? goToGradeEdit(scope.row, '终期成绩') : null" style="cursor: pointer;">
                {{ scope.row.finalScore !== 0.0 ? scope.row.finalScore : '待批阅' }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="peerReviewGrade" label="互评成绩" width="150px">
            <template #default="scope">
              <span :style="getStyle(scope.row.peerReviewScore)">
                {{ scope.row.peerReviewScore !== 0.0 ? scope.row.peerReviewScore : '待批阅' }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="总成绩" width="100px">
            <template #header>
              <el-dropdown @command="handleCommand">
                <span class="el-dropdown-link" style="cursor: pointer;">
                  总成绩
                  <el-icon class="el-icon-arrow-down el-icon--small" />
                </span>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item v-for="item in dropdownItems" :key="item.command" :command="item.command" @click="change1(item.command)" :style="item.command === calculationMethod ? { backgroundColor: '#2590F1', color: 'white' } : {}">
                      <span >
                        {{ item.label }}
                      </span>
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </template>
            <template #default="scope">
              <div :style="getTotalGradeStyle(scope.row)">
                {{ calculateTotalGrade(scope.row) }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="评语">
            <template #default="scope">
              <el-text v-model="scope.row.comments">
                {{ scope.row.comments }}
              </el-text>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import axios from 'axios'

const router = useRouter()
const route = useRoute()

const tableData = ref([])
const displayData = ref([])
const calculationMethod = ref('')

const change1 = (changes) => {
  console.log(calculationMethod.value)
  calculationMethod.value = changes
  console.log(calculationMethod.value)
}

const dropdownItems = ref([
  { command: 'average', label: '平均分计算' },
  { command: 'weighted', label: '权衡比计算' },
  { command: 'max', label: '最大分计算' }
])

const fetchData = async () => {
  try {
    const response = await axios.get('http://localhost:8080/rating/listAll')
    tableData.value = transformData(response.data)
    displayData.value = tableData.value
    updateDisplayData()
    console.log(1)
  } catch (error) {
    console.error('Failed to fetch data:', error)
  }
}

const transformData = (data) => {
  return data.map(group => ({
    id: group.id,
    groupId: group.groupId,
    groupName: group.groupName,
    studentId: `${group.leaderId}`,
    name: group.name,
    initialScore: group.initialScore,
    midTermScore: group.midTermScore,
    finalScore: group.finalScore,
    peerReviewScore: group.peerReviewScore,
    totalScore: group.totalScore,
    comments: group.comments,
    strategyType: group.strategyType,
    expanded: false,
    children: group.children.map(child => ({
      id: child.id,
      position: child.position,
      studentId: `${child.studentId}`,
      name: child.name,
      initialScore: child.initialScore,
      midTermScore: child.midTermScore,
      finalScore: child.finalScore,
      peerReviewScore: child.peerReviewScore,
      totalScore: child.totalScore,
      comments: child.comments,
      groupId: child.groupId,
      strategyType: child.strategyType,
    }))
  }))
}

const calculateTotalGrade = (row) => {
  if (row.initialScore === 0.0 || row.midTermScore === 0.0 || row.finalScore === 0.0 || row.peerReviewScore === 0.0) {
    return '未完成'
  }
  return row.totalScore
}

const handleCommand = async (command) => {
  calculationMethod.value = command
  updateTableData()
  setTimeout(()=>{fetchData()},500)
}

const getStyle = (score) => {
  return score === null ? { color: 'red' } : {}
}

const getTotalGradeStyle = (row) => {
  return calculateTotalGrade(row) === '未完成' ? { color: 'gray' } : {}
}

const toggle = (group) => {
  group.expanded = !group.expanded
  updateDisplayData()
}

const updateDisplayData = () => {
  displayData.value = []
  tableData.value.forEach(group => {
    calculationMethod.value=group.strategyType
    console.log(1)
    displayData.value.push(group)
    if (group.expanded) {
      group.children.forEach(member => {
        displayData.value.push(member)
      })
    }
  })
}

const updateTableData=()=>{
  tableData.value.forEach(group => {
    group.strategyType=calculationMethod.value
      group.children.forEach(member => {
       member.strategyType=calculationMethod.value
      })
    axios.post('http://localhost:8080/rating/update', group)
  })
}

const updateGrade = (member) => {
  const parentGroup = tableData.value.find(group => group.children.some(child => child.id === member.id))
  if (parentGroup) {
    const allGrades = parentGroup.children.map(child => child.initialScore)
    if (!allGrades.includes(null)) {
      parentGroup.initialScore = parentGroup.children[0].initialScore
      parentGroup.midTermScore = parentGroup.children[0].midTermScore
      parentGroup.finalScore = parentGroup.children[0].finalScore
      parentGroup.peerReviewScore = parentGroup.children[0].peerReviewScore
    }
  }
}

const goToGradeEdit = (row, gradeType) => {
  if (row.children) {
    router.push({ name: 'grade-edit', query: { row: JSON.stringify(row), gradeType } })
  }
}

onMounted(() => {
  fetchData()
})

const gradeTypeToProp = (type) => {
  switch (type) {
    case '初期成绩':
      return 'initialScore'
    case '中期成绩':
      return 'midTermScore'
    case '终期成绩':
      return 'finalScore'
    default:
      return ''
  }
}
</script>

<style scoped>
.grading-table {
  padding: 20px;
}

.header {
  margin-bottom: 20px;
}

.el-icon {
  margin-left: 5px;
}
</style>
